<template>
  <div id="user-profile">
    <van-form @submit="onSubmit">
      <van-field label="用户" v-model="userForm.id" type="text" readonly/>
      <van-field label="用户" v-model="userForm.name" type="text" placeholder="请输入用户"
                 :rules="[{ pattern:regNamePwd,required: true, message: '无效用户名' }]"/>

      <van-field label="邮箱" v-model="userForm.email" type="email" placeholder="请输入邮箱"
                 :rules="[{ pattern:regEmail, message: '无效邮箱' }]"/>

      <van-field label="电话" v-model="userForm.phone" type="tel" placeholder="请输入电话"
                 :rules="[{ pattern:regPhone, message: '无效手机号码' }]"/>

      <van-field name="radio" label="性别">
        <template #input>
          <van-radio-group v-model="userForm.gender" direction="horizontal">
            <van-radio :name="1">男</van-radio>
            <van-radio :name="0">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field label="昵称" v-model="userForm.nickName" type="text" placeholder="请输入昵称"></van-field>

      <van-field name="uploader" label="头像">
        <template #input>
          <van-uploader v-model="fileList"
                        :max-count="1"
                        :before-read="beforeRead"
                        :after-read="afterRead"
                        :before-delete="beforeDelete"
          />
        </template>
      </van-field>

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
//导入用户接口
import * as UserAPI from "@/api/user.js";
import * as FileAPI from "@/api/file.js";
import {setStorageUser} from '@/utils/storage.js'

export default {
  data() {
    return {
      userForm: { //表单中的字段名与数据库中用户表的字段名要求一致
        id: null,
        name: "",
        email: "",
        phone: "",
        gender: 1,
        avatar: "",
        nickName: "",
      },

      //规则:字母数字‘6~12
      regNamePwd: /^[a-z0-9]{3,12}$/i,
      regPhone: /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/,
      regEmail: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,

      //上传图片后回显
      fileList: [],
    };
  },


  //生命周期钩子函数，实例被创建好了后被调用 this.
  created() {
    UserAPI.getMyDetail().then(result => {
      this.userForm = result.data; //看接口文档，知道data是对应的用户对象

      //在上传图片组件中显示图片头像
      this.fileList = [];
      if (this.userForm.avatar) {
        this.fileList.push({
          url: this.$fullUrl(this.userForm.avatar)
        });
      }
    });
  },

  methods: {
    // 文件读取完成后的回调函数
    afterRead(file) {
      file.status = 'uploading';
      file.message = '上传中...';
      // console.log(file)
      let formData = new FormData();
      formData.append("file", file.file);

      FileAPI.uploadFile(formData).then(result => {
        file.status = '';
        file.message = '';
        //重新生成显示的图片url
        this.fileList = [];
        let url = result.data.url;
        this.fileList.push({
          url: this.$fullUrl(url)
        })
        //设置用户表中的字段值
        this.userForm.avatar = url;

      });
    },

    // 文件读取前的回调函数，返回 false 可终止文件读取
    beforeRead(file) {
      // console.log("上传前", file);
      const imgFormat = /image\/(png|jpg|jpeg)$/;
      if (!imgFormat.test(file.type)) {
        this.$toast.fail('请上传 jpg/jpeg/png 格式图片');
        return false;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$toast.fail('文件大小不能超过 2M');
        return false;
      }
      return true;
    },

    //文件删除前的回调函数，返回 false 可终止文件读取
    beforeDelete() {
      // 删除云端存储的文件
      let pathes = [];
      this.fileList.forEach(item => {
        pathes.push(item.url)
      })
      FileAPI.deleteFile(pathes).then(result => {
        console.log(result.message)
      }).catch(error => {
        console.log(error)
      })

      this.fileList = [];
      //设置用户表中的字段值
      this.userForm.avatar = "";

    },

    //处理提交保存
    onSubmit() {
      //注意传递过去的参数user的属性名
      let user = this.userForm;
      UserAPI.update(user).then(() => {
        this.$toast("更新成功！");
        let {id, name, avatar} = user;
        setStorageUser({id, name, avatar});
        //1秒后路由跳转 到我的页面
        setTimeout(() => {
          this.$router.push({
            name: "user"
          });
        }, 1000);
      });
    },
  },
};
</script>
<style lang="less" scoped>

</style>
